package com.nicolas.common.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;

import com.nicolas.common.model.Client;
import com.nicolas.common.model.Country;



@Controller
@RequestMapping("/client")
public class ControllerForm {
	
	
	@RequestMapping(value="/new", method = RequestMethod.GET)
	public String initForm(ModelMap model){
		model.addAttribute("cliente",new Client());
		List<Country> countriesList = new ArrayList<Country>( Arrays.asList(Country.values() ));
		model.addAttribute("countriesList", countriesList);
		return "form";
	}
	
	@RequestMapping(value="/show", method = RequestMethod.GET)
	public String showClients(ModelMap model){
		
		
		EntityManagerFactory emf= Persistence
                .createEntityManagerFactory("manager1");
		
		EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();
		List<Client> clientes = em.createQuery("from Client").getResultList();
        tx.commit();
        
        model.addAttribute("clientes", clientes);
        
        return "show";
		
	}
	
	@RequestMapping(method = RequestMethod.POST)
	 public String processSubmit(
	   @ModelAttribute("cliente") Client c,
	   BindingResult result, 
	   SessionStatus status) {

		EntityManagerFactory emf = Persistence
                .createEntityManagerFactory("manager1");
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        
        tx.begin();
        
        em.persist(c);
        
        tx.commit();
		return "succes";
	 }
	
}